package com.ynwt.thread;

import com.github.sd4324530.fastweixin.api.CustomAPI;
import com.github.sd4324530.fastweixin.api.MediaAPI;
import com.github.sd4324530.fastweixin.api.enums.MediaType;
import com.github.sd4324530.fastweixin.api.response.UploadMediaResponse;
import com.github.sd4324530.fastweixin.message.ImageMsg;
import com.github.sd4324530.fastweixin.message.TextMsg;
import com.ynwt.domain.User;
import com.ynwt.repository.UserDao;
import com.ynwt.service.EventService;
import com.ynwt.service.MsgService;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by huangying on 2017/5/11.
 */
@Component
@Scope(scopeName = "prototype")
public class SendQrcodeImgThread implements Runnable {

    private final static Logger LOG = LoggerFactory.getLogger(SendQrcodeImgThread.class);

    private String openid;

    public SendQrcodeImgThread setOpenid(String openid) {
        this.openid = openid;
        return this;
    }

    @Override
    public void run() {
        sendQrcodeImage(openid);
    }

    public void sendQrcodeImage(String openid) {

        User user = userDao.findOne(openid);

        //如果qrcode_url为空或者为null，则重新创建二维码
        if (null == user.getQrcodeUrl() || "".equals(user.getQrcodeUrl().trim())) {
            LOG.warn("method: sendQrcodeImage. msg: qrcodeUrl is null or blank, which will be create in a second. (参数二维码路径不存在, 将会重新创建) user: {}.\n", user.getNickname());
            eventService.createQrcode(openid);
        }

        File qrcodeImg = new File(user.getQrcodeUrl()); //获取参数二维码

        //如果磁盘上的二维码不存在，则重新创建二维码
        if (!qrcodeImg.exists()) {
            LOG.warn("method: sendQrcodeImage. msg: qrcode is not exist in disk, which will be create in a second. (参数二维码不存在磁盘上, 将会根据指定路径创建) user: {}.\n", user.getNickname());
            eventService.createQrcode(openid);
        }

        File bgImg = new File(backGroundImage); //背景图片

        URL headImgUrl = null;
        try {
            headImgUrl = new URL(user.getHeadImgUrl());
        } catch (MalformedURLException e) {
            LOG.warn("method: sendQrcodeImage. msg: new headImgUrl object exception. (头像转化成URL出错) user: {}.\n", user.getNickname(), e);
        }
        File headTmpImg = null; //获取头像
        try {
            headTmpImg = File.createTempFile("head_img_" + user.getOpenid(), ".png");
            if (null != headImgUrl) {
                FileUtils.copyURLToFile(headImgUrl, headTmpImg);
            } else {
                LOG.warn("method: sendQrcodeImage. msg: headImgUrl is null （头像URL对象为null）. user: {}.\n", user.getNickname());
            }
        } catch (IOException e) {
            LOG.warn("method: sendQrcodeImage. msg: create headTmpImg exception. (创建临时头像文件出错) user: {}.\n", user.getNickname(), e);
        }

        try {
            BufferedImage qrcodeBuff = ImageIO.read(qrcodeImg);
            BufferedImage headBuff = ImageIO.read(headTmpImg);
            BufferedImage bgBuff = ImageIO.read(bgImg);

            Graphics2D g = bgBuff.createGraphics();
            g.setColor(Color.orange);
            g.setFont(new Font("楷体", Font.BOLD, 40));
            g.drawString(user.getNickname(), 180, 715);
            g.setColor(Color.black);
            g.drawImage(headBuff, 45, 650, 115, 115, null);
            g.drawImage(qrcodeBuff, 375, 780, 300, 300, null);
            g.dispose();

//            File adTmpImg = File.createTempFile("adImg_" + 1, ".png");//换成下面那一句
            File adTmpImg = File.createTempFile("adImg_" + user.getUnionid(), ".png");
            FileOutputStream fos = new FileOutputStream(adTmpImg);
            ImageIO.write(bgBuff, "PNG", fos);
            fos.close();

            UploadMediaResponse mediaResponse = mediaAPI.uploadMedia(MediaType.IMAGE, adTmpImg);
            FileUtils.forceDeleteOnExit(qrcodeImg);
            FileUtils.forceDeleteOnExit(adTmpImg);

            customAPI.sendCustomMessage(openid, new ImageMsg(mediaResponse.getMediaId()));
            customAPI.sendCustomMessage(openid, new TextMsg("【" + user.getNickname() + "】同学，环球君已经给你发送了专属于你的邀请卡喽，赶紧邀请你的小伙伴一起和你玩转逸贝，轻松获取环球数据助力学习公益赠品吧！点击<a href=\"http://mp.weixin.qq.com/s/6K4iLMKdvNIuNlKFNI-ABg\">赠品清单</a>即可知道你的逸贝能得到环球君送的什么礼物哦～"));

        } catch (IOException e) {
            LOG.warn("method: sendQrcodeImage. msg:  Compose adImg exception(合成图片出错). user: {}.\n", user.getNickname(), e);
        }
    }

    @Value("${backGroundImage}")
    private String backGroundImage;

    @Autowired
    private MediaAPI mediaAPI;

    @Autowired
    private CustomAPI customAPI;

    @Autowired
    private UserDao userDao;

    @Autowired
    private EventService eventService;
}
